import React from 'react';   
import {connect} from 'dva';
import {Link, browserHistory} from 'dva/router';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message} from 'antd';
const R = require('ramda');
import moment from 'moment'
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import RightContacts from "../../../utils/RightConstants";
import EditCustomer from '../../../components/supplier/components/EditCustomer';
import BizParams from '../../../components/commons/BizParams'
import CustomerDetail from '../../../components/supplier/components/CustomerDetail';
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";


const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
export default connect(({customerManage, businessAgreement}) => ({customerManage, businessAgreement}))(
    Form.create()(class customerManage extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                open: false,
            }
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    status: 1,
                    businessType: Constants.NUMBER_ONE
                }
            });
        }

        handleAdd = () => {
            this.setState({open: true});
        }

        handleResetFields = () => {
            if(this.editCustomer)this.editCustomer.handleResetFields();
        }

        handleCancel = (flag) => {
            if(flag){
                this.handleResetFields();
            }
            this.setState({ open: false});
        }

        onView = (record) => {
            this.handleOpenDetail(record, true,  {}, "1", true);
        }

        onEdit = (record) => {
            this.handleOpenDetail(record, false, {}, "1", false);
        }

        handleOpenDetail = (record, customerDisabled, searchConditions, tabActiveKey, editCustomerDisable) => {
            this.props.dispatch({type: 'customerManage/getCustomerById', payload: {id: record.id, isApproval: true}});
            this.props.dispatch({type: 'customerManage/getLinkmanList', payload: {cstId: record.id, page :  this.props.customerManage.linkmanPage}});//查询联系人列表
            this.props.dispatch({type: 'businessAgreement/getAgreementlList', payload: {cstid: record.id, status: 1}});

            this.refs.customerDetail.handleOpen(customerDisabled, searchConditions, tabActiveKey, record.id, editCustomerDisable, "customerManage",record.status,);
        }

        handleSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.customerManage.page;
            newPage.page = 1;
            let time=values.time;


            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    customerNO: values.customerNO,
                    cstName: values.cstName,
                    cstManage: values.cstManage,
                    cstWaiter: values.cstWaiter,
                    status: values.status,
                    businessType: Constants.NUMBER_ONE,
                    page: newPage,
                    beginTime:R.isNil(time)||R.isEmpty(time)?null:time[0].format(dateFormat),
                    endTime:R.isNil(time)||R.isEmpty(time)?null:time[1].format(dateFormat),
                }
            });
        };

        handleConfirm = () => {
            if(this.editCustomer){
                if(this.editCustomer.checkCustomerInfo(this.props.dispatch,this.onSuccess) ==  true){
                    this.handleSearch();
                }

            }



        };

        onSuccess=()=>{
            this.handleSearch();
            this.handleCancel();
            this.handleResetFields();
        };


        columns = [
            {title: '供应商编码', dataIndex: 'customerno', key: 'customerno'},

            // {title: '代理协议号', dataIndex: 'companyna', key: 'companyna', render(record) {
            //     return ("xx");
            // }},

            {title: '供应商名称', dataIndex: 'companyname', key: 'companyname',},

            {title: '供应商类型', render(record) {
                if(R.isNil(record.companytypeName) || R.isEmpty(record.companytypeName)){
                    return "未分配"
                }else{
                    return record.companytypeName;
                }
            }},

            {title: '采购经理', render(record) {
                if(R.isNil(record.managerName) || R.isEmpty(record.managerName)){
                    return "未分配";
                }else{
                    return record.managerName;
                }
            }},

            {title: '跟单经理', render(record) {
                if(R.isNil(record.waiterName) || R.isEmpty(record.waiterName)){
                    return "未分配";
                }else{
                    return record.waiterName;
                }
            }},

            {title: '创建时间', dataIndex: 'createtime', key: 'createtime'},

            {title: '操作', key: 'key_oprator',

            render: (text, record, index) => {
                let deleteButton =
                    <RightBox resource={RightContacts.SUPPLIER.SUPPLIER_MANAGE_DELETE} >
                    <Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={() => {
                            if(record.csttype === '1'){
                                message.info("当前是会员供应商，不允许删除！");
                                return;
                            }
                            this.props.dispatch({
                                type: 'customerManage/deleteCustomerById',
                                payload: {
                                    id : record.id,
                                    onSuccess:()=>{
                                        this.handleSearch();
                                    }
                                }
                            });
                        }} okText="是" cancelText="否">
                        <a href="#">删除</a>

                    </Popconfirm></RightBox>;


                let editButton=<RightBox resource={RightContacts.SUPPLIER.SUPPLIER_MANAGE_UPDATE} split={false}>
                    {record.status === "1" || record.status === "3" ?
                        <span><a href="#" onClick={this.onEdit.bind(this, record)}>编辑</a> <span className="ant-divider"/></span>: ''}

                </RightBox>;



                deleteButton = record.status === "1" || record.status === "3" ? deleteButton : "";
                let split = deleteButton === "" ? "" : <span className="ant-divider"/>;
                return (
                    <span>
                        {record.status === "1" || record.status === "3" ? editButton:''}
                        {deleteButton}

                        {record.status === "2" || record.status === "4" || record.status === "5" ?
                            <a href="#" onClick={this.onView.bind(this, record)}>查看</a>: ''}
                    </span>
                );
            }
        }
        ];

        render () {
            let dataSouce = R.isNil(this.props.customerManage.dataSource) ? {} : this.props.customerManage.dataSource;
            let formItemLayout = {labelCol: {span: 6}, wrapperCol: {span: 18}};
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time=values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.customerManage.page.size,
                total: this.props.customerManage.page.totalRow,
                showSizeChanger: true,
                current: this.props.customerManage.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.customerManage.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            status: values.status,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage,
                            beginTime:R.isNil(time)||R.isEmpty(time)?null:time[0].format(dateFormat),
                            endTime:R.isNil(time)||R.isEmpty(time)?null:time[1].format(dateFormat),
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.customerManage.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            status: values.status,
                            businessType: Constants.NUMBER_ONE,
                            page: newPage,
                            beginTime:R.isNil(time)||R.isEmpty(time)?null:time[0].format(dateFormat),
                            endTime:R.isNil(time)||R.isEmpty(time)?null:time[1].format(dateFormat),
                        }
                    });
                }
            }
            return (
                <div>

                <Row>
                    <Col span={7}><FormItem {...formItemLayout} label={'供应商编码'}>{getFieldDecorator('customerNO')(<Input/>)}</FormItem></Col>
                    <Col span={7}><FormItem {...formItemLayout} label={'供应商名称'}>{getFieldDecorator('cstName')(<Input/>)}</FormItem></Col>
                </Row>
                <Row>
                    <Col span={7}><FormItem {...formItemLayout} label={'采购经理'}>{getFieldDecorator('cstManage')(<Input/>)}</FormItem></Col>
                    <Col span={7}><FormItem {...formItemLayout} label={'跟单经理'}>{getFieldDecorator('cstWaiter')(<Input/>)}</FormItem></Col>
                </Row>
                <Row>
                    <Col span={7}>
                        <FormItem {...formItemLayout} label={'创建时间'}>
                            {getFieldDecorator('time', {})(
                                <RangePicker
                                    style={{width: '100%'}}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                            )}
                        </FormItem>
                    </Col>

                </Row>
                <Row>
                    <Col span={7}>
                    <FormItem {...formItemLayout} label={'状态'}>
                    {getFieldDecorator('status', {
                            initialValue: "1"
                        })(

                            <RadioGroup style={{width: 800}}>
                                <Radio value="1">待申请</Radio>
                                <Radio value="2">待审核</Radio>
                                <Radio value="3">待补充资料</Radio>
                                <Radio value="4">审核通过</Radio>
                                <Radio value="5">审核不通过</Radio>
                            </RadioGroup>
                        )}
                        </FormItem>
                    </Col>
                    <Col span={7} style={{float: 'right'}}>
                        <Button type="primary" icon="search" style={{marginRight: 5}} onClick={this.handleSearch.bind(this)}>查询</Button>
                        <RightBox resource={RightContacts.SUPPLIER.SUPPLIER_MANAGE_ADD}><Button type="primary" icon="plus" style={{marginRight: 5}} onClick={this.handleAdd.bind(this)}>添加供应商</Button></RightBox>

                    </Col>
                </Row>

                <Table dataSource={this.props.customerManage.suppilerList} columns={this.columns} bordered={true}
                       size={'middle'} pagination={pagination}/>

                <CustomerDetail ref={"customerDetail"} cstId={dataSouce.cstid} {...this.props.customerManage}
                                businessAgreement={this.props.businessAgreement} dispatch={this.props.dispatch}
                                handleSearch = {this.handleSearch}/>

                <Modal maskClosable={false} visible={this.state.open} title={"编辑供应商"} width={800}
                       wrapClassName="vertical-center-modal" onCancel={this.handleCancel} onOk={this.handleConfirm}>
                    <EditCustomer wrappedComponentRef={(inst) => this.editCustomer = inst} type={"add"} businessType={"1"}
                                  handleSearch = {this.handleSearch}/>
                </Modal>
            </div>
            )
        }
    })


)
